<template>
  <el-dialog
    :visible.sync="isShow"
    :title="mode === 'add' ? '新增部门' : '编辑部门'"
    width="500px"
  >
    <el-form label-width="100px" :model="form" :rules="rules" ref="form">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          @focus="focusEvent"
          v-model="form.manager"
          placeholder="请选择"
        >
          <el-option
            v-for="i in userList"
            :key="i.id"
            :label="i.username"
            :value="i.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments.js'
export default {
  name: 'DialogItem',
  props: {
    initList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      // add就是新增弹框, edit就是编辑弹框
      mode: 'add',
      bol: true,
      isShow: false,
      userList: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let temp = ''
              if (this.mode === 'add') {
                temp = this.initList.filter(item => {
                  return item.pid === this.item.pid
                })
              } else {
                temp = this.initList.filter(item => {
                  return item.pid === this.item.pid && item.id !== this.item.id
                })
              }
              const result = temp.some(item => {
                return item.name === value.trim()
              })
              result
                ? callback(new Error(`请不要输入重复的部门名称:` + value))
                : callback()
            },
            trigger: 'change'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              let result = ''
              if (this.mode === 'add') {
                result = this.initList.some(item => {
                  return item.code === value
                })
              } else {
                result = this.initList.some(item => {
                  return item.code === value && item.id !== this.item.id
                })
              }
              result ? callback(new Error('请不要输入重复的code')) : callback()
            }
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  watch: {
    isShow: {
      // deep:true  deep为true是深度监听,监听堆与栈的变化,默认只监听栈的变化
      handler (newVal) {
        if (!newVal) {
          // 关闭弹窗时还原数据
          this.form = {
            name: '',
            code: '',
            manager: '',
            introduce: '',
            pid: ''
          }
          // 1.还原数据为初次渲染时的值 2.清除表单验证
          this.$refs.form.resetFields()
        }
      }
    }
  },
  mounted () {
    this.$bus.$on('show', (bol, item, mode = 'add') => {
      this.isShow = bol
      this.item = item
      this.mode = mode
      // console.log(item.id)
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  beforeDestroy () {
    this.$bus.$off('show')
  },
  methods: {
    async focusEvent () {
      if (this.userList.length === 0) {
        const res = await sysUserSimple()
        this.userList = res.data
        console.log('员工列表', res)
      }
    },
    submit () {
      this.$refs.form.validate(async result => {
        if (result) {
          if (this.mode === 'add') {
            this.form.pid = this.item.id
            await companyDepartmentPost(this.form)
            /* 
            新增成功:
            1.提示
            2.关闭弹框
            3.刷新父级列表
            */
            // this.$message.success('验证成功')
            // this.isShow = false
            // this.$emit('getData')
          } else {
            await companyDepartmentPut(this.form)
            // this.$message.success('编辑成功')
            // this.isShow = false
            // this.$emit('getData')
          }
          // 简化代码
          this.$message.success(this.mode === 'add' ? '新增成功' : '编辑成功')
          this.isShow = false
          this.$emit('getData')
        }
      })
    }
  }
}
</script>

<style></style>
